from rest_framework import serializers
from .models import KnowledgeBase, Tag, Document, DocumentChunk


class TagSerializer(serializers.ModelSerializer):
    """标签序列化器"""

    class Meta:
        model = Tag
        fields = '__all__'
        read_only_fields = ['user', 'created_at']

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class KnowledgeBaseSerializer(serializers.ModelSerializer):
    """知识库序列化器"""
    document_count = serializers.SerializerMethodField()

    class Meta:
        model = KnowledgeBase
        fields = '__all__'
        read_only_fields = ['user', 'created_at', 'updated_at']

    def get_document_count(self, obj):
        return obj.document_set.count()

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        # 如果设置为默认知识库,将其他知识库设置为非默认
        if validated_data.get('is_default'):
            KnowledgeBase.objects.filter(user=validated_data['user'], is_default=True).update(is_default=False)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        if validated_data.get('is_default'):
            KnowledgeBase.objects.filter(user=instance.user, is_default=True).exclude(id=instance.id).update(is_default=False)
        return super().update(instance, validated_data)


class DocumentChunkSerializer(serializers.ModelSerializer):
    """文档分块序列化器"""

    class Meta:
        model = DocumentChunk
        fields = '__all__'
        read_only_fields = ['created_at']


class DocumentSerializer(serializers.ModelSerializer):
    """文档序列化器"""
    tags_info = TagSerializer(source='tags', many=True, read_only=True)
    tag_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False,
        help_text='标签ID列表'
    )
    knowledge_base_name = serializers.CharField(source='knowledge_base.name', read_only=True)

    class Meta:
        model = Document
        fields = '__all__'
        read_only_fields = ['user', 'file_type', 'file_size', 'md5_hash', 'page_count', 'word_count',
                            'status', 'error_message', 'content', 'vector_indexed', 'vector_id',
                            'created_at', 'updated_at']

    def create(self, validated_data):
        tag_ids = validated_data.pop('tag_ids', [])
        validated_data['user'] = self.context['request'].user

        # 计算文件MD5
        file_obj = validated_data['file']
        validated_data['md5_hash'] = Document.calculate_md5(file_obj)
        validated_data['file_size'] = file_obj.size

        # 根据文件扩展名确定文件类型
        file_name = file_obj.name
        if file_name.endswith('.pdf'):
            validated_data['file_type'] = 'pdf'
        elif file_name.endswith('.docx'):
            validated_data['file_type'] = 'docx'
        elif file_name.endswith('.txt'):
            validated_data['file_type'] = 'txt'

        document = super().create(validated_data)

        # 添加标签
        if tag_ids:
            document.tags.set(tag_ids)

        return document


class DocumentUploadSerializer(serializers.Serializer):
    """文档上传序列化器"""
    file = serializers.FileField(required=True, help_text='文档文件')
    knowledge_base_id = serializers.IntegerField(required=True, help_text='知识库ID')
    title = serializers.CharField(required=False, help_text='文档标题(可选,默认使用文件名)')
    tag_ids = serializers.ListField(
        child=serializers.IntegerField(),
        required=False,
        help_text='标签ID列表'
    )

    def validate_file(self, value):
        """验证文件类型和大小"""
        from django.conf import settings

        # 验证文件大小
        if value.size > settings.MAX_UPLOAD_SIZE:
            raise serializers.ValidationError(f'文件大小不能超过 {settings.MAX_UPLOAD_SIZE / 1024 / 1024}MB')

        # 验证文件类型
        file_ext = value.name.split('.')[-1].lower()
        if file_ext not in settings.ALLOWED_FILE_TYPES:
            raise serializers.ValidationError(f'不支持的文件类型: {file_ext}')

        return value
